package com.heaven.web;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.heaven.client.Client;
import com.heaven.community.SnsSpace;
import com.heaven.dao.SpaceDAO;
import com.heaven.dao.UserlogDAO;
import com.heaven.service.CommonService;
import com.heer.utils.UtilMisc;

@Controller
public class CpAvatarController extends BaseController {
	
	private static Log logger = LogFactory.getLog(CpAvatarController.class);
	
	@Autowired
	private CommonService commonService;

	@Autowired
	private Client client;

	@Autowired
	private SpaceDAO spaceDAO;

	@Autowired
	private UserlogDAO userlogDAO;

	@RequestMapping("/upload")
	public String upload(HttpServletRequest request) throws IOException,
			FileUploadException {
		// 错误信息
		String errorMsg = "";
		
		// 文件保存目录路径
		String prefix = "/attachment/avatar/origin/";
		// 绝对路径
		String savePath = request.getSession().getServletContext().getRealPath("/") + prefix;
		String photoId = UUID.randomUUID().toString();
		// 上传的文件名
		String tempName = photoId + ".jpg";

		// 上传后图片的绝对地址
		String picRealPath = request.getContextPath() + prefix + tempName;
		

		// 判断是否为单个文件
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			errorMsg = saveFile(request, savePath, tempName);
			if (errorMsg.equals("")) {
				response().getWriter().println(
				"<script type=\"text/javascript\">window.parent.hideLoading();" +
				"window.parent.buildAvatarEditor(\""+ photoId + "\",\"" + picRealPath + "\",\"photo\");" +
				"</script>';");
			} else {
				// 插入图片，关闭层
				response().getWriter().println(
				"<script type='text/javascript'>alert('对不起, 上传失败, " + errorMsg + "');</script>");
			}
		}
		return null;
	}
	
	/**
	 * 保存头像 一大一小
	 * @param request
	 * @param input
	 * @return
	 * @throws IOException
	 * @throws FileUploadException
	 */
	@RequestMapping("/saveavatar")
	public String saveAvatar(HttpServletRequest request, InputStream input) throws IOException,
			FileUploadException {
		
		String type = request.getParameter("type");
		if(null == type) type = "small";
		//这里传过来会有两种类型，一先一后, big和small, 保存成功后返回一个json字串，客户端会再次post下一个.
		String photoId = request.getParameter("photoId");
		// 生成图片存放路径
		// 错误信息
		String errorMsg = "";
		// 文件保存目录路径
		String prefix = "/attachment/avatar/"+type+"/";
		
		saveAvatarStream(request, input, photoId, prefix);
		
        return null;
	}

	/**
	 * 保存摄像头图片
	 * @param request
	 * @throws IOException
	 * @throws FileUploadException
	 */
	@RequestMapping("/camera")
	public String camera(HttpServletRequest request, InputStream input) throws IOException,
			FileUploadException {
		
		
		
		String photoId = UUID.randomUUID().toString();
		String prefix = "/attachment/avatar/origin/";
		saveAvatarStream(request, input, photoId, prefix);
		return null;
	}
	
	@RequestMapping("/avatar")
	public String avatar(HttpServletRequest request, InputStream input) throws IOException,
			FileUploadException {
		String type = get("type");
		
		return null;
	}
	
	private void saveAvatarStream(HttpServletRequest request,
			InputStream input, String photoId, String prefix)
			throws FileNotFoundException, IOException {
		// 绝对路径
		String savePath = request.getSession().getServletContext().getRealPath("/") + prefix;
		// 上传的文件名
		String tempName = photoId + ".jpg";
		// 上传后图片的绝对地址
		String picRealPath = request.getContextPath() + prefix + tempName;
		
		FileOutputStream writer = new FileOutputStream(savePath + tempName);
		IOUtils.copy(input, writer);
		writer.write(new byte[1024]);
		writer.close();
		
        //输出新保存的图片位置, 测试时注意改一下域名路径, 后面的statusText是成功提示信息.
        //status 为1 是成功上传，否则为失败.
        String jsondata = 
        	"{\"data\":{" +
        		"\"photoId\": \""+photoId+"\","+
        		"\"urls\": [\""+picRealPath+"\"]},"+
        	"\"status\":1,"+
        	"\"statusText\":\"\\u4e0a\\u4f20\\u6210\\u529f!\""+
        	"}";
        response().getWriter().println(jsondata);
        //response().getWriter().println("{\"data\":{\"urls\":[\"\\/avatar_test\\/avatar_big\\/1244127038_big.jpg\"]},\"status\":1,\"statusText\":\"\\u4e0a\\u4f20\\u6210\\u529f!\"}");
	}
	
	
	private String saveFile(HttpServletRequest request, String savePath, String tempName) {
		// 错误信息
		String errorMsg = "";
		// 文件最大值
		long maxSize = 1000000;
		// 定义文件上传的类型
		String[] types = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };
		
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List items;
		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e1) {
			logger.debug("上传文件 失败", e1);
			return "上传文件 失败:"+ e1.getMessage();
		}

		// Process the uploaded items
		Iterator iter = items.iterator();
		while (iter.hasNext()) {
			FileItem item = (FileItem) iter.next();
			// 原文件名
			String fileName = item.getName();

			// 文件大小
			long fileSize = item.getSize();

			if (!item.isFormField()) {
				// 检查文件名
				if (item.getName() == "" || item.getString() == null) {
					errorMsg = "请选择文件。";
					break;
				}

				// 检查目录
				File uploadDir = new File(savePath);
				if (!uploadDir.isDirectory()) {
					errorMsg = "上传目录不存在。";
					break;
				}
				// 检查目录写权限
				if (!uploadDir.canWrite()) {
					errorMsg = "上传目录没有写权限。";
					break;
				}
				// 检查文件大小
				if (item.getSize() > maxSize) {
					errorMsg = "上传文件大小超过限制。";
				}

				// 获得文件扩展名
				// String fileExt = fileName.substring(fileName.indexOf(".")+1);
				String fileExt = "jpg";
				if (!Arrays.<String> asList(types).contains(fileExt.toLowerCase())) {
					errorMsg = "上传文件扩展名是不允许的扩展名。";
				}

				// 服务器上临时文件名
				// String tempName = new Date().getTime()+"."+fileExt;

				// 检查是否已上传
				File file = new File(savePath + "\\" + tempName);
				if (file.exists()) {
					errorMsg = "临时文件可能不是上传文件。";
				}

				// 上传文件
				try {
					File uploadedFile = new File(savePath, tempName);

					item.write(uploadedFile);
				} catch (Exception e) {
					errorMsg = "上传文件失败。";
				}
			}
		}
		return errorMsg;
	}
	
	
	@RequestMapping("/cp_avatar")
	public String excute(HttpServletRequest request) {
		before(request);
		SnsSpace space = Global.getSpace();

		if (submitcheck("avatarsubmit")) {
			if (test(get("guidemode"))) {
				showmessage("do_success",
						"space.html?do=home&view=guide&step=2", 0);
			} else {
				showmessage("do_success", "cp.html?ac=avatar", 0);
			}
		}

		// 头像
		String uc_avatarflash = client.uc_avatar(Global.getSupeUid(),
				(empty(Config.get("avatarreal")) ? "virtual" : "real"));
		set("uc_avatarflash", uc_avatarflash);
		// 判断用户是否设置了头像
		SnsSpace setarr = new SnsSpace();
		boolean avatar_exists = commonService.ckavatar(space.getUid());
		// 是否需要更新
		boolean isModify = false;
		if (avatar_exists) {
			if (!space.getAvatar()) {
				setarr.setAvatar(true);
				setarr.setUpdatetime(Global.getTimestamp());
				isModify = true;
			}
		} else {
			if (space.getAvatar()) {
				setarr.setAvatar(false);
				isModify = true;
			}
		}

		if (isModify) {
			setarr.setUid(space.getUid());
			spaceDAO.update(setarr);
			// 变更记录
			if (!empty(Config.get("my_status"))) {
				userlogDAO.create(UtilMisc.toMap("uid", Global.getSupeUid(),
						"action", "update", "dateline", Global.getTimestamp()));
			}
		}
		set("checkperm_domainlength", commonService.getUserGroup()
				.getDomainlength());
		return "/template/default/cp_avatar";
	}
}
